import { createRouter, createWebHistory } from 'vue-router'
import Welcome from '@/views/Welcome.vue'
import projectService from '@/services/projectService'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/welcome'
    },
    {
      path: '/welcome',
      name: 'welcome',
      component: Welcome
    },
    {
      path: '/ide',
      name: 'ide',
      component: () => import('@/views/IDE.vue')
    },
  ]
})

// 路由守卫：检查是否有当前项目
router.beforeEach((to, _from, next) => {
  // 如果是首次访问根路径，总是显示欢迎页面
  if (to.path === '/' && !_from.name) {
    next('/welcome')
    return
  }
  
  const currentProject = projectService.getCurrentProject()
  
  // 如果没有项目且不是访问欢迎页面，重定向到欢迎页面
  if (!currentProject && to.name !== 'welcome') {
    next('/welcome')
  }
  // 如果有项目且访问欢迎页面，重定向到IDE
  else if (currentProject && to.name === 'welcome') {
    next('/ide')
  }
  else {
    next()
  }
})

export default router
